import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
import { getFullImageUrl, request } from '../../../utils/request';

export default {
    components: {
        uniPopup,
        uniIcons
    },
    data() {
        return {
            availableBalance: 192.32, // 可用余额
            lastMonthIncome: 0.00, // 上月收入金额
            pendingAmount: 0.00, // 待结算金额
            balanceDetails: {
                list: [], // 存储所有月份的明细数据
                total: 0, // 总记录数
                pages: 0, // 总页数
                time: '', // 最新交易时间
                amount: '' // 最新交易金额
            },
            withdrawalDetails: {
                time: '', // 最新提现时间
                amount: '' // 最新提现金额
            },
            // 分页相关变量
            currentPage: 1,
            pageSize: 10, // 每页条数
            hasMore: true, // 初始化为true，确保可以加载第一页
            withdrawAmount: 0, // 确保初始化为数字类型
            bankFeeRate: 0.6, // 银行卡服务费率
            platformFeeRate: 0.2, // 平台费率
            selectedPaymentMethod: 'wechat', // 选择的支付方式
            passwordDots: Array(6).fill(false), // 密码输入点
            password: '', // 输入的密码
            isWechatBound: true, // 微信是否已绑定
            isAlipayBound: true, // 支付宝是否已绑定

        };
    },
    async onLoad() {
        // 检查用户是否完善了身份信息
        await this.checkIdentityStatus();
        // 获取用户余额信息
        await this.getUserBalance();
        await this.getBalanceDetail();
        // 获取提现明细信息
        await this.getWithdrawalDetail();
    },
    computed: {
        // 判断是否有选中的支付方式
        hasSelectedPaymentMethod() {
            return !!this.selectedPaymentMethod;
        },
        // 判断是否有任何支付方式已绑定
        hasAnyPaymentBound() {
            return this.isWechatBound || this.isAlipayBound;
        },
        // 判断确认按钮是否激活
        isConfirmButtonActive() {
            // 条件：提现金额>0 且 至少有一个支付方式已绑定 且 已选择支付方式
            return this.withdrawAmount > 0 && this.hasAnyPaymentBound && this.hasSelectedPaymentMethod;
        },
        // 添加格式化提现金额的计算属性
        formattedWithdrawAmount() {
            // 确保金额是数字类型，默认为0
            const amount = Number(this.withdrawAmount);
            return isNaN(amount) ? '0.00' : amount.toFixed(2);
        }
    },
    
    methods: {
        getFullImageUrl,
        // 检查用户身份信息状态
        async checkIdentityStatus() {
            try {
                // 调用后端API检查身份信息
                const res = await request({
                    url: '/User/checkIdentity',
                    method: 'GET'
                });
                
                if (res.code === 1) {
                    console.log('检查身份信息成功', res);
                    const isIdentityCompleted = res.data.is_verified;
                    if (!isIdentityCompleted) {
                        // 显示身份信息弹窗
                        this.$refs.identityPopup.open();
                    }
                }
            } catch (error) {
                console.error('检查身份信息失败', error);
                // 出错时默认假设未完善身份信息
                this.$refs.identityPopup.open();
            }
        },

        // 获取用户余额信息
        async getUserBalance() {
            try {
                const res = await request({
                    url: '/User/wallet',
                    method: 'GET'
                })
                if (res.code === 200) {
                    this.availableBalance = Number(res.data.balance); // 将字符串转换为数字
                    this.lastMonthIncome = res.data.last_month_income;
                    this.pendingAmount = res.data.pending_settlement;
                }
            } catch (error) {
                console.error('获取用户余额信息失败', error);
            }
        },

        // 获取提现明细信息
        async getWithdrawalDetail() {
            try {
                const res = await request({
                    url: '/Withdrawals/getWithdrawalLogList',
                    method: 'GET',
                    data: {
                        page: 1,
                        limit: 1
                    }
                })
                if (res.code === 1 && res.data && res.data.list && res.data.list.length > 0) {
                    // 设置最新一条提现记录的时间和金额
                    const latestRecord = res.data.list[0];
                    this.withdrawalDetails.time = latestRecord.create_time;
                    this.withdrawalDetails.amount = '¥' + latestRecord.amount;
                }
            } catch (error) {
                console.error('获取提现明细失败', error);
            }
        },
        
        // 获取余额明细
        async getBalanceDetail(isLoadMore = false) {
            // 如果没有更多数据且是加载更多，则直接返回
            if (!this.hasMore && isLoadMore) {
                console.log('没有更多数据了');
                return;
            }
            
            // 如果是加载更多，则页码加1
            const page = isLoadMore ? this.currentPage + 1 : 1;
            
            try {
                console.log(`正在加载第${page}页数据`);
                const res = await request({
                    url: `/User/balanceDetails?page=${page}&limit=${this.pageSize}`,
                    method: 'GET'
                })
                if (res.code === 1) {
                    // 更新总记录数和总页数
                    this.balanceDetails.total = res.data.total;
                    this.balanceDetails.pages = res.data.pages;
                    console.log(`总页数: ${this.balanceDetails.pages}, 当前页: ${page}`);
                    
                    // 如果是首次加载，重置列表
                    if (!isLoadMore) {
                        this.balanceDetails.list = [];
                        // 设置最新一条记录的时间和金额（如果有数据）
                        if (res.data.list.length > 0 && res.data.list[0].details.length > 0) {
                            this.balanceDetails.time = res.data.list[0].details[0].createtime;
                            this.balanceDetails.amount = res.data.list[0].details[0].money;
                        }
                    }
                    
                    // 追加新数据
                    if (res.data.list.length > 0) {
                        this.balanceDetails.list = [...this.balanceDetails.list, ...res.data.list];
                        this.currentPage = page;
                        // 判断是否还有更多数据
                        this.hasMore = this.currentPage < this.balanceDetails.pages;
                        console.log(`加载成功，是否还有更多数据: ${this.hasMore}`);
                    } else {
                        this.hasMore = false;
                        console.log('没有更多数据了');
                    }
                } else {
                    console.error('获取数据失败，code不为1');
                }
            } catch (error) {
                console.error('获取余额明细失败', error);
            }
        },

        // 关闭身份信息弹窗
        closeIdentityPopup() {
            this.$refs.identityPopup.close();
        },

        // 跳转到完善身份信息页面
        goToCompleteIdentity() {
            uni.navigateTo({
                url: '/pages/pageMy/Authn/Authn'
            });
            this.closeIdentityPopup();
        },

        // 跳转到余额明细页面
        goToBalanceDetail() {
            uni.navigateTo({
                url: '/pages/pageMy/balanceDetails/balanceDetails'
            });
        },
        
        // 跳转到提现记录页面
        goToWithdrawalDetail() {
            uni.navigateTo({
                url: '/pages/pageMy/withdrawalRecord/withdrawalRecord'
            });
        },

        // 打开提现弹窗
        openWithdrawPopup() {
            this.$refs.withdrawPopup.open();
        },

        // 关闭提现弹窗
        closeWithdrawPopup() {
            this.$refs.withdrawPopup.close();
        },

        // 打开密码弹窗前检查
        openPasswordPopup() {
            if (!this.hasSelectedPaymentMethod) {
                uni.showToast({ title: '请选择支付方式', icon: 'none' });
                return;
            }
            // 检查提现金额是否超过可用余额
            if (this.withdrawAmount > this.availableBalance) {
                uni.showToast({ title: '提现金额不能超过可用余额', icon: 'none' });
                return;
            }
            this.$refs.passwordPopup.open();
        },

        // 关闭密码输入弹窗
        closePasswordPopup() {
            this.$refs.passwordPopup.close();
            // 重置密码
            this.password = '';

        },

        // 选择支付方式
        selectPaymentMethod(method) {
            this.selectedPaymentMethod = this.selectedPaymentMethod === method ? '' : method;
        },

        // 密码输入处理
        inputPassword(num) {
            if (this.password.length < 6) {
                this.password += num.toString();
                // 输入6位密码后自动验证
                if (this.password.length === 6) {
                    this.submitPassword();
                }
            }
        },

        // 删除最后一位密码
        deletePassword() {
            if (this.password.length > 0) {
                this.password = this.password.slice(0, -1);
            }
        },
        // 提交密码验证
        submitPassword() {
            // 调用后端密码验证接口
            request({
                url: '/wallet/verifypassword',
                method: 'POST',
                data: {
                    password: this.password
                },
                success: (res) => {
                    if (res.data.code === 1) {
                        // 密码正确，调用提现接口
                        request({
                            url: '/wallet/withdraw',
                            method: 'POST',
                            data: {
                                amount: this.withdrawAmount,
                                paymentMethod: this.selectedPaymentMethod,
                                password: this.password
                            },
                            success: (withdrawRes) => {
                                if (withdrawRes.data.code === 1) {
                                    // 提现成功，关闭弹窗，显示成功提示
                                    this.$refs.passwordPopup.close();
                                    this.$refs.withdrawPopup.close();
                                    this.$refs.successPopup.open();
                                    // 刷新余额
                                    this.getUserBalance();
                                    // 关闭成功提示并重置密码
                                    setTimeout(() => {
                                        this.$refs.successPopup.close();
                                        this.password = '';
                                    }, 1000);
                                } else {
                                    // 提现失败
                                    uni.showToast({
                                        title: withdrawRes.msg || '提现失败，请重试',
                                        icon: 'none'
                                    });
                                    this.password = '';
                                }
                            },
                            fail: () => {
                                // 提现请求失败
                                uni.showToast({
                                    title: '网络异常，提现失败',
                                    icon: 'none'
                                });
                                this.password = '';
                            }
                        });
                    } else {
                        // 密码错误，显示错误提示
                        this.$refs.errorPopup.open();
                        setTimeout(() => {
                            this.$refs.errorPopup.close();
                            this.password = '';
                        }, 1000);
                    }
                },
                fail: () => {
                    // 密码验证请求失败
                    this.$refs.errorPopup.open();
                    setTimeout(() => {
                        this.$refs.errorPopup.close();
                        this.password = '';
                    }, 1000);
                }
            });
        },
        // 模拟检查身份信息
        mockCheckIdentity() {
            return new Promise(resolve => {
                // 模拟网络延迟
                setTimeout(() => {
                    // 模拟未完善身份信息
                    resolve(false);
                }, 500);
            });
        },
        // 添加上拉加载更多的处理函数
        onReachBottom() {
            this.getBalanceDetail(true);
        },
        // 模拟提交提现
        mockSubmitWithdraw() {
            return new Promise(resolve => {
                // 模拟网络延迟
                setTimeout(() => {
                    resolve(true);
                }, 1000);
            });
        },

        // 全部提现
        withdrawAll() {
            // 确保转换为数字类型
            this.withdrawAmount = Number(this.availableBalance) || 0;
        },
        // 绑定支付方式
        bindPayment(method) {
            if (method === 'wechat') {
                // 微信绑定逻辑
                uni.navigateTo({ url: '/pages/bindWechat' });
            } else if (method === 'alipay') {
                // 支付宝绑定逻辑
                uni.navigateTo({ url: '/pages/bindAlipay' });
            }
        },
        handleAmountInput(e) {
            // 确保值是数字
            const value = Number(e.detail.value);
            this.withdrawAmount = isNaN(value) ? 0 : value;
        }
    }
};
